package com.wlf.admin.common.freemarker;

import java.util.Locale;

import freemarker.core.*;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
import freemarker.template.utility.NumberUtil;

/**
 * 功能描述: 金额格式化
 *
 * @author wlf 2023/11/29 18:00
 */
public class AmtTemplateNumberFormatFactory extends TemplateNumberFormatFactory {

    public static final AmtTemplateNumberFormatFactory INSTANCE
            = new AmtTemplateNumberFormatFactory();

    private AmtTemplateNumberFormatFactory() {
    }

    @Override
    public TemplateNumberFormat get(String params, Locale locale, Environment env)
            throws InvalidFormatParametersException {
        TemplateFormatUtil.checkHasNoParameters(params);
        return HexTemplateNumberFormat.INSTANCE;
    }

    private static class HexTemplateNumberFormat extends TemplateNumberFormat {

        private static final HexTemplateNumberFormat INSTANCE = new HexTemplateNumberFormat();

        private HexTemplateNumberFormat() {
        }

        @Override
        public String formatToPlainText(TemplateNumberModel numberModel)
                throws UnformattableValueException, TemplateModelException {
            Number n = TemplateFormatUtil.getNonNullNumber(numberModel);
            try {
                return cn.hutool.core.util.NumberUtil.decimalFormat("#.00####", n);
            } catch (ArithmeticException e) {
                throw new UnformattableValueException(n + " 不适合金额");
            }
        }

        @Override
        public boolean isLocaleBound() {
            return false;
        }

        @Override
        public String getDescription() {
            return "金额格式化";
        }

    }

}